package io.github.wanggit.antcms.server.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.wanggit.antcms.server.Constants;
import io.github.wanggit.antcms.server.domain.AntMedia;
import io.github.wanggit.antcms.server.service.MediaService;
import io.github.wanggit.antcms.server.service.impl.utils.MediaUtil;
import io.github.wanggit.antcms.server.web.vm.ListMediasVM;
import io.github.wanggit.antcms.server.web.vm.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("media")
public class MediaController {

    @Autowired private MediaService mediaService;

    @Autowired private MediaUtil mediaUtil;

    @PostMapping("list")
    public Result listMedias(@RequestBody ListMediasVM listMediasVM) {
        QueryWrapper<AntMedia> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("upload_time");
        Page<AntMedia> page =
                new Page<>(
                        null == listMediasVM.getPage() || listMediasVM.getPage() <= 0
                                ? 1
                                : listMediasVM.getPage(),
                        null == listMediasVM.getSize() || listMediasVM.getSize() <= 0
                                ? Constants.DEFAULT_PAGE_SIZE
                                : listMediasVM.getSize());
        Page<AntMedia> mediaPage = mediaService.page(page, queryWrapper);
        mediaPage.getRecords().forEach(it -> it.setUrl(mediaUtil.wrapPreviewUrl(it.getUrl())));
        return Result.ok(mediaPage);
    }

    @GetMapping("detail")
    public Result detailMedia(@RequestParam("id") Long id) {
        return Result.ok(mediaService.getById(id));
    }

    @PostMapping("update")
    public Result updateMedia(@RequestBody AntMedia antMedia) {
        AntMedia entity = mediaService.getById(antMedia.getId());
        entity.setAlt(antMedia.getAlt());
        entity.setTitle(antMedia.getTitle());
        entity.setRemark(antMedia.getRemark());
        mediaService.saveOrUpdate(entity);
        return Result.ok();
    }

    @PostMapping("save")
    public Result saveMedia(@RequestParam("file") MultipartFile multipartFile) {
        AntMedia media = mediaService.saveMedia(multipartFile);
        media.setUrl(mediaUtil.wrapPreviewUrl(media.getUrl()));
        return Result.ok(media);
    }

    @GetMapping("del")
    public Result deleteMedia(@RequestParam("id") Long id) {
        mediaService.deleteMedia(id);
        return Result.ok();
    }

    @PostMapping("mdel")
    public Result deleteMedias(@RequestBody List<Long> ids) {
        mediaService.deleteMedias(ids);
        return Result.ok();
    }
}
